import datetime
import json
import random
import time
from flask import Blueprint, request, jsonify, redirect

from db import db
from util.comm import get_ali_object
from util.myredis import r

vip_blue = Blueprint("vip", __name__)

# 充值vip
@vip_blue.route("/buy", methods=['POST'])
def getviplist():
    data = json.loads(request.data)
    userid = data["user_id"]
    year = data["year"]
    money = 299
    tmoney = money * int(year)
    order_no = str(int(time.time())) + str(userid)
    sql = "insert into vip_record(userid, year, money, active_money, status, order_on) values(%d, %d, %f, %f, 1, '%s')" % (
    int(userid), year, tmoney, tmoney, order_no)
    db.add(sql)
    db.commit()
    # 支付
    alipay = get_ali_object()
    order_no = order_no + "," + str(1)
    # 生成支付的url
    query_params = alipay.direct_pay(
        subject=str(userid) + "购买vip服务",  # 商品简单描述
        out_trade_no=order_no,  # 用户购买的商品订单号（每次不一样） 20180301073422891
        total_amount=float(tmoney),  # 交易金额(单位: 元 保留俩位小数)
    )
    # 支付宝网关地址（沙箱应用）
    pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(
        query_params)
    pkey = 'orderpayfail'
    r.sortedset_add(pkey, order_no, int(time.time()))
    return jsonify({"code": 200, 'url': pay_url})


@vip_blue.route("/callback")
def callback():
    data = request.args
    datames = {k: v for k, v in data.items()}
    # 删除字典中key为sign的记录
    sign = datames.pop('sign')
    print(sign)
    # 鉴权
    pay = get_ali_object()
    print(pay)
    flag = pay.verify(datames, sign)
    print(flag)
    if flag == True:
        # 订单号
        order_no = datames["out_trade_no"]
        order_no_index = order_no.split(",")
        # 支付宝流水号
        transaction_no = datames["trade_no"]
        # 事务处理
        try:
            if order_no_index[1] == 1:
                # 订单号更新vip订单表
                # record = VipRecord.query.filter(VipRecord.order_no == order_no).first()
                # record.status = 2
                # record.transaction_no = transaction_no
                sql = db.findOne("select * from vip_record where order_on='%s'" % order_no)
                up_sql = "update vip_record set status=2, transaction_no='%s' where order_on='%s'" % (transaction_no, order_no)
                db.add(up_sql)
                # 更新用户表
                # user_info = UsersModel.query.filter(UsersModel.id == record.userid).first()
                # user_info.level = 2
                use_sql = "update user set level=2 where id=%d" % sql.userid
                db.add(use_sql)
                # 更新vip表
                # vip = Vip.query.filter(Vip.userid == record.userid, status=1).first()
                vip_sql = "update vip set status=1 where userid=%d" % sql.userid
                db.add(vip_sql)
                vip = "select * from vip where userid=%d" % sql.userid
                sql_se = db.findOll(sql)
                db.commit()
                if not sql_se:
                    etime = datetime.date.strftime(datetime.datetime.now(), "%Y-%m-%d %H:%m:%s").split("-")
                    year = int(etime[0]) + int(sql.year)
                    print(year)
                    str1 = "-"
                    retime = str1.join(etime)
                    print(retime, ">>>")
                    # vip = Vip(userid=sql.userid, s_time=datetime.datetime.now(), e_time=retime)
                    stime = datetime.datetime.now()
                    vip_into = "insert into vip(userid, s_time, e_time) values(%d, '%s', '%s')" % (sql.userid, stime, retime)
                    db.add(vip_into)
                    db.commit()
                    print("<<<>>>")
                else:
                    # 结束时间+购买年限
                    etime = vip.e_time.split("-")
                    year = int(etime[0]) + int(sql.year)
                    vip.e_time = year
                    print(">>><<<")
                db.session.commit()
            if order_no_index[1] == 2:
                # 订单号更新订单表
                # record = Orders.query.filter(Orders.number == order_no).first()
                # record.status = 3
                record_sql = "update orders set status=3 where number='%s'" % order_no
                db.add(record_sql)
                db.commit()
        except:
            db.rollback()
    else:
        print("鉴权失败")
    return redirect('http://localhost:8080/#/vip')
